<?php


namespace app\index\controller;


use app\common\logic\PaypalAdvanced;
use think\Controller;

class Pay extends Controller
{
    public function index()
    {
        return $this->fetch('index/pay/index');
    }

    public function getToken()
    {
        try {
            $orderResponse =(new PaypalAdvanced())->getToken();
            echo json_encode($orderResponse['jsonResponse']);
        } catch (Exception $e) {
            echo json_encode(['error' => $e->getMessage()]);
            http_response_code(500);
        }
    }

    public function orders()
    {
        $data = json_decode(file_get_contents('php://input'), true);
        $cart = $data['cart'] ?? [];
        try {
            $orderResponse =(new PaypalAdvanced())->createOrder($cart);
            echo json_encode($orderResponse['jsonResponse']);
        } catch (Exception $e) {
            echo json_encode(['error' => $e->getMessage()]);
            http_response_code(500);
        }
    }

    public function capture()
    {
        $orderID = input('orderID', '', 'trim');
        if (!$orderID) {
            $endpoint = $_SERVER['REQUEST_URI'];
            if (str_ends_with($endpoint, '/capture')) {
                $urlSegments = explode('/', $endpoint);
                end($urlSegments); // Will set the pointer to the end of array
                $orderID = prev($urlSegments);
            }
        }
        try {
            $captureResponse = (new PaypalAdvanced())->captureOrder($orderID);
            echo json_encode($captureResponse['jsonResponse']);
        } catch (Exception $e) {
            echo json_encode(['error' => $e->getMessage()]);
            http_response_code(500);
        }
    }

    public function cancel()
    {
        $this->redirect('pay/index');
    }
}